package com.bsy.videostation.ui.fragment

import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction.TRANSIT_FRAGMENT_FADE
import com.bsy.framework.base.BaseMvvmFragment
import com.bsy.framework.helper.AppHelper
import com.bsy.videostation.view_type.AllViewType
import com.bsy.videostation.viewmodel.MainViewModel
import com.dg.videostation.R
import com.dg.videostation.databinding.FragmentAllContainerBinding
import me.jessyan.autosize.AutoSize

/**
 * Created by since on 2024/6/2.
 * Copyright
 * 描述：
 */
class AllContainerFragment : BaseMvvmFragment<FragmentAllContainerBinding, MainViewModel>() {
    private var fragmentManager: FragmentManager? = null
    override fun onAttach(context: Context) {
        super.onAttach(context)
        fragmentManager = parentFragmentManager
    }

    override fun initViewModel() {
        mViewModel = AppHelper.getApplicationViewModel(MainViewModel::class.java)
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mViewModel.allEvent.value = AllViewType.HOME_PAGE.value
    }

    override fun initObserver() {
        mViewModel.allEvent.observe(viewLifecycleOwner) {
            val fragment = when (it) {
                AllViewType.VIDEO_LIST_PAGE.value -> VideoListFragment.newInstance(2)
                else -> AllFragment.newInstance()
            }
            val existingFragment = fragmentManager?.findFragmentById(R.id.all_container)
            val transaction = fragmentManager?.beginTransaction()?.setTransition(TRANSIT_FRAGMENT_FADE)
            if (existingFragment == null)
                transaction?.add(R.id.all_container, fragment)?.commit()
            else
                transaction?.replace(R.id.all_container, fragment)?.commit()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        AutoSize.autoConvertDensity(activity, 768F, false)
        return getContentView(inflater, container)
    }

    override fun onPause() {
        mViewModel.allScrollToFirstPosition.value = 0
        super.onPause()
    }

    override fun onFragmentVisible(isVisibleToUser: Boolean) {
        if (isVisibleToUser)
            mViewModel.allScrollToFirstPosition.value = 1
    }

    companion object {
        fun newInstance() = AllContainerFragment()
    }
}